package patternrecognition.symbols;

import java.util.ArrayList;
import java.util.List;

import patternrecognition.Util;
import patternrecognition.symbols.forms.Rectangle;

public abstract class Symbol {

	private static final List<Symbol> sSymbols;
	static {
		sSymbols = new ArrayList<Symbol>(6);
		sSymbols.add(new C());
		sSymbols.add(new I());
		sSymbols.add(new L());
		sSymbols.add(new O());
		sSymbols.add(new T());
		sSymbols.add(new X());
	}

	private List<String> rows;

	private List<String> getRows() {
		return rows;
	}

	private void setRows(List<String> rows) {
		this.rows = rows;
	}

	public static Symbol getSymbol(final int[][] matrix)
			throws IllegalArgumentException {

		List<String> rows = Util.parseMatrix(matrix);

		List<Rectangle> rectangles = Util.parseRows(rows);

		if (areAdjacent(rectangles)) {
			for (Symbol possibleSymbol : sSymbols) {
				if (possibleSymbol.isSymbol(rectangles)) {
					try {
						Symbol symbol = (Symbol) possibleSymbol.clone();
						symbol.setRows(rows);
						return symbol;
					} catch (CloneNotSupportedException e) {
						e.printStackTrace();
					}
				}
			}
		}

		throw new IllegalArgumentException("Unknown Symbol!");
	}

	protected static boolean areAdjacent(final List<Rectangle> rectangles) {
		int size = rectangles.size();
		for (int i = 0; i + 1 < size; i++) {
			if (!rectangles.get(i).isAdjacent(rectangles.get(i + 1)))
				return false;
		}
		return true;
	}

	protected abstract boolean isSymbol(final List<Rectangle> rectangles);

	public abstract String getID();

	public void print() {
		System.out.println("Symbol: " + getID());
		System.out.println();
		for (String row : getRows()) {
			System.out.println(row);
		}
	}
}
